package com.ls.sync;

//线程通信

//资源类
class Share {
    private int number = 0;

    //+1
    public synchronized void incr() throws InterruptedException {
        while (number != 0) {//用while防止虚假唤醒
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + " :: " + number);
        this.notifyAll();
    }

    //-1
    public synchronized void decr() throws InterruptedException {
        while (number != 1) {
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + " :: " + number);
        this.notifyAll();
    }
}

public class ThreadDemo1 {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    share.decr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "aa").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "bb").start();




    }
}
